from django.http import JsonResponse
from drf_spectacular.utils import extend_schema,inline_serializer
from rest_framework.decorators import action
from rest_framework.mixins import (CreateModelMixin, ListModelMixin,
                                   RetrieveModelMixin, UpdateModelMixin)
from rest_framework.viewsets import GenericViewSet
from backend.cews.services.ImpWorkService import query_real_time_repair_order_imp_work, toggle_complete_repair_order_imp_work
from utils.autoschema import AutoDocSchema, custom_response_serailizer
from utils.decorators import error_response, request_data, activities_logging
from backend.cews.models import RepairOrderEDoc, StockItem, StockItemEDoc, Log
from .serializers import (RepairOrderImpWorkSerializer)
from rest_framework import serializers
from django_filters import rest_framework as filters
import django_filters

class CustomFilter(filters.FilterSet):
    repair_order = filters.Filter(field_name='repair_order', lookup_expr='exact')
    class Meta:
        model = RepairOrderEDoc
        fields = ['repair_order']
        

class RepairOrderImpWorkViewSet(
    RetrieveModelMixin,
    ListModelMixin,
    UpdateModelMixin,
    GenericViewSet,
    # CreateModelMixin
):
    serializer_class = RepairOrderImpWorkSerializer
    queryset = RepairOrderEDoc.objects.all()
    filterset_class = CustomFilter
    filter_backends = [django_filters.rest_framework.DjangoFilterBackend]
    
    
    @activities_logging(
        log_type=Log.LogType.MAINTENANCE,
        category_type=Log.CategoryType.IMPWORK,
        action_type=Log.ActionType.COMPLETE,
        action="toggle_complete_repair_order_imp_work",
        description="complete repair order improvement work"
    )
    @action(detail=False, methods=['post'], schema=AutoDocSchema(),
            url_name='toggle_complete_api',
            url_path='toggle_complete')
    @request_data(keys=['id'],types={'id':int})
    @error_response()
    def toggle_complete_api(self,request,id):
        edoc = toggle_complete_repair_order_imp_work(id)
        return JsonResponse(data=self.serializer_class(edoc).data,status=200)
    
        
    @action(detail=False, methods=['post'], schema=AutoDocSchema())
    @request_data(keys=['repair_order'])
    @error_response()
    def get_imp_work_realtime(self,request,repair_order):
        repair_order_imp_works = query_real_time_repair_order_imp_work(repair_order)
        return JsonResponse(data=self.serializer_class(repair_order_imp_works,many=True).data,status=200,safe=False)
        
        
        
        